<template>
  <el-cascader
    expand-trigger="hover"
    filterable
    :options="options"
    :props="props"
    clearable
    @change="change"
  />
</template>

<script>
import { listProduct } from '@/api/iot/iotProductUserApi'
import { listSeries } from '@/api/iot/iotProductSeriesUserApi'
import { getUserId } from '@/util/storage'

export default {
  name: 'ProductSeriesCascade',
  data() {
    return {
      productList: [],
      props: {},
      options: [],
      userId: getUserId()
    }
  },
  created() {
    const that = this
    this.props = {
      checkStrictly: true,
      lazy: true,
      lazyLoad(node, resolve) {
        const { level, value } = node
        if (level === 0) {
          listProduct({
            userId: that.userId
          }).then(res => {
            const { code, data } = res
            if (code === '200') {
              const productList = []

              data.forEach(product => {
                productList.push({
                  value: product.productId,
                  label: product.name,
                  leaf: false
                })
              })
              const allProductItem = {}
              allProductItem.value = null
              allProductItem.label = that.$t('all')
              allProductItem.leaf = true
              productList.unshift(allProductItem)
              resolve(productList)
            }
          })
        } else if (level === 1) {
          if (!value) {
            resolve([])
            return
          }
          listSeries({
            userId: that.userId,
            productId: value
          }).then(res => {
            const { code, data } = res
            if (code === '200') {
              const seriesList = []
              data.forEach(series => {
                seriesList.push({
                  value: series.seriesId,
                  label: series.name,
                  leaf: true
                })
              })
              resolve(seriesList)
            }
          })
        }
        resolve([])
      }
    }
  },
  methods: {
    change(data) {
      this.$emit('change', {
        productId: data[0],
        seriesId: data[1]
      })
    }
  }

}
</script>


